#include "stm32f10x.h"                  // Device header


//******************************************引脚配置层***********************************************************************
/*
SS引脚电平设置
*/
void MySPI_SS_W(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA, GPIO_Pin_4, (BitAction)BitValue);
}


/*
SPI初始化函数
*/
void MySPI_Init(void)
{
	/*-----------------GPIO引脚配置---------------------------*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
	// SCK MOSI : 选择硬件控制,复用推挽输出
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	// NSS(SS) : 选择软件控制,推挽输出
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	// MISO : 上拉输入
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	// NSS初始状态, 不选中从设备, 即不开始通信
	MySPI_SS_W(1);
	/*--------------------------SPI配置---------------------------*/
	SPI_InitTypeDef SPI_InitStruture;
	SPI_InitStruture.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
	// 配置为模式0
	SPI_InitStruture.SPI_CPHA = SPI_CPHA_1Edge;
	SPI_InitStruture.SPI_CPOL = SPI_CPOL_Low;
	SPI_InitStruture.SPI_CRCPolynomial = 7;
	SPI_InitStruture.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStruture.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStruture.SPI_FirstBit = SPI_FirstBit_MSB;
	SPI_InitStruture.SPI_Mode = SPI_Mode_Master;
	SPI_InitStruture.SPI_NSS = SPI_NSS_Soft;
	SPI_Init(SPI1, &SPI_InitStruture);
	
	SPI_Cmd(SPI1, ENABLE);
//	// NSS初始状态, 不选中从设备, 即不开始通信
//	MySPI_SS_W(1);
}


//*********************************************(通信层)时序单元层***********************************************************************
/*
SPI起始信号
*/
void MySPI_Start(void)
{
	MySPI_SS_W(0);
}

/*
SPI终止信号
*/
void MySPI_Stop(void)
{
	MySPI_SS_W(1);
}


/*
SPI交换字节
*/
uint8_t MySPI_Swap_ByteSend(uint8_t ByteSend)
{
	while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);		// TXE = 1;
	SPI_I2S_SendData(SPI1, ByteSend);									// 就发送数据
	while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);	// RXNE = 1;
	return SPI_I2S_ReceiveData(SPI1);
}
